# !/usr/bin/python3
# _*_ coding: utf-8 _*_
# @Time     : 2021/10/27 上午8:25
# @Author   : HHR
# ___MSG___ : ""
import hashlib
import json
import shutil
import time
from docx.shared import Pt
import os
from docx import Document
from docx.shared import Inches, RGBColor
from docx.oxml.ns import qn
from docxcompose.composer import Composer
try:
    from comtypes import client
except ImportError:
    client = None
try:
    from win32com.client import Dispatch, DispatchEx
    import pythoncom
except ImportError:
    Dispatch = None
    DispatchEx = None
    pythoncom = None

import docx
from docx.enum.table import WD_TABLE_ALIGNMENT, WD_ROW_HEIGHT_RULE
from docx.shared import Cm
import PyPDF2, subprocess


def delete_paragraph(paragraph):
    p = paragraph._element
    p.getparent().remove(p)
    paragraph._p = paragraph._element = None



def red_chromatography(file_type, fpath, fwh):
    """
    file_type：模板类型，
    fpath：正文所在路径，
    fwh：发文号
    """

    # 创建word文档对象
    try:
        if file_type in ['1', '2', '6']:
            document = Document()
        else:
            document = Document(r'.\static\administrative\UploadAccessory\页脚.docx')  # 使用包含页脚的模板
            for p in document.paragraphs:
                delete_paragraph(p)  # 删除模板空行段落，不删插入图片后会有空行
    except Exception as e:
        print(e)
        return None

    if file_type == '1':
        file_name = '京山市人民医院文件.png'
    elif file_type == '2':
        file_name = '华中科技大学协和京山医院文件.png'
    elif file_type == '3':
        file_name = '华中科技大学协和京山医院.png'
    elif file_type == '4':
        file_name = '华中科技大学协和京山医院京山市人民医院.png'
    elif file_type == '5':
        file_name = '中共京山市人民医院委员会.png'
    elif file_type == '6':
        file_name = '中共京山市人民医院委员会文件.png'
    else:
        print('类型错误')
        file_name = '中共京山市人民医院委员会文件.png'

    # 插入图片:Inches表示以英寸作为图片的单位
    img_path = os.path.join(r'.\static\administrative\img', file_name)
    document.add_picture(img_path, width=Inches(6.0))

    # 添加发文号段落
    p = document.add_paragraph()
    p.alignment = 2
    text = p.add_run(fwh)
    text.font.name = 'Microsoft YaHei'
    text.element.rPr.rFonts.set(qn('w:eastAsia'), u'楷体')

    # 判断是否要添加红色横线
    if file_type in ['1', '2', '6']:
        img_path = os.path.join(r'.\static\administrative\img', '横线.png')
        document.add_picture(img_path, width=Inches(6.0))

    # 旧文件的内容写入
    try:
        old_document = Document(fpath)
        for p in old_document.paragraphs:
            document.add_paragraph(p.text)
    except Exception as e:
        print("e: ", e)
        return None

    # 新文件保存
    docx_save_path = os.path.join(os.getcwd(), 'media/docx_path')
    if not os.path.exists(docx_save_path):
        os.mkdir(docx_save_path)
    return_path = os.path.join(docx_save_path, f'{fpath.split("/")[-1]}')
    document.save(return_path)
    download_url = '/media/docx_path/' + f'{fpath.split("/")[-1]}'
    return download_url


class ParseWord():
    def start_parse(self, file_type, word_path, fwh):
        """
        file_type: 红头文件的编号：1、2、3、4、5、6
        word_path： 正文链接地址
        fwh： 文号
        """
        master = self.add_word_head(file_type,fwh)
        composer = Composer(master)
        doc2 = self.add_word_text(word_path)
        composer.append(doc2)

        file_path = os.path.join(os.getcwd(),'media/docx_path')
        if not os.path.exists(file_path):
            os.makedirs(file_path)
        new_path = file_path + "/" + (word_path.split("/")[-1])
        composer.save(new_path)
        return '/media/docx_path/'+ (word_path.split("/")[-1])

    def delete_paragraph(self,paragraph):
        p = paragraph._element
        p.getparent().remove(p)
        paragraph._p = paragraph._element = None

    def add_word_head(self, file_type,fwh):
        if file_type in ['1', '2', '6']:
            # 创建word文档对象
            master = Document(r'.\static\administrative\UploadAccessory\页码.docx')
        else:
            # 使用包含页脚的模板
            master = Document(r'.\static\administrative\UploadAccessory\页脚.docx')
            for p in master.paragraphs:
                # 删除模板空行段落，不删插入图片后会有空行
                self.delete_paragraph(p)

        if file_type == '1':
            file_name = '京山市人民医院文件.png'
        elif file_type == '2':
            file_name = '华中科技大学协和京山医院文件.png'
        elif file_type == '3':
            file_name = '华中科技大学协和京山医院.png'
        elif file_type == '4':
            file_name = '华中科技大学协和京山医院京山市人民医院.png'
        elif file_type == '5':
            file_name = '中共京山市人民医院委员会.png'
        else:
            file_name = '中共京山市人民医院委员会文件.png'

        img_path = os.path.join(r'.\static\administrative\img', file_name)
        print(img_path)
        # 插入图片:Inches表示以英寸作为图片的单位
        master.add_picture(img_path, width=Inches(6.0))

        # 添加段落
        p = master.add_paragraph()
        p.paragraph_format.space_before = Pt(0)
        p.paragraph_format.space_after = Pt(0)
        if '京医发' in fwh:
            p.alignment = 1
            text = p.add_run("\n\n"+fwh)
            text.font.name = '仿宋_GB2312'
            text.font.size = Pt(16)
            text.element.rPr.rFonts.set(qn('w:eastAsia'), u'仿宋_GB2312')
        elif '京医文' in fwh:
            p.alignment = 0
            fwh = "\n\n" + fwh + ' ' * 22 + '签发人:叶  霖'
            text = p.add_run(fwh)
            text.font.name = '仿宋_GB2312'
            text.font.size = Pt(16)
            text.element.rPr.rFonts.set(qn('w:eastAsia'), u'仿宋_GB2312')
        elif '纪要' in fwh:
            p.alignment = 2
            fwh = fwh.replace(fwh.split("〔")[0], "会议纪要")
            text = p.add_run(fwh+"\n\n")
            text.font.name = '仿宋_GB2312'
            text.font.size = Pt(16)
            text.element.rPr.rFonts.set(qn('w:eastAsia'), u'仿宋_GB2312')
        else:
            p.alignment = 2
            text = p.add_run("\n\n"+fwh)
            text.font.name = '仿宋_GB2312'
            text.font.size = Pt(16)
            text.element.rPr.rFonts.set(qn('w:eastAsia'), u'仿宋_GB2312')

        if file_type in ['1', '2', '6']:
            file_name = '横线.png'
            img_path = os.path.join(r'.\static\administrative\img', file_name)
            print(img_path)
            # 插入图片:Inches表示以英寸作为图片的单位
            master.add_picture(img_path, width=Inches(6.0))
        return master

    def add_word_text(self,word_path):
        doc2 = Document(word_path)

        for i in range(len(doc2.paragraphs)):
            doc2.paragraphs[i].paragraph_format.space_before = Pt(0)
            doc2.paragraphs[i].paragraph_format.space_after = Pt(0)
            style_name = doc2.paragraphs[i].style.name
            if i > 0:
                if style_name in ['Heading 4', "Body Text Indent 2", "Normal (Web)"]:
                    doc2.paragraphs[i].height = Pt(28)
                    doc2.paragraphs[i].height_rule = WD_ROW_HEIGHT_RULE.EXACTLY

                    inline = doc2.paragraphs[i].runs
                    for i in inline:
                        i.font.italic = False
                        i.font.color.rgb = RGBColor(0, 0, 0)
                        i.font.bold = False
                        text = i.text
                        i.text = text
        return doc2

    def create_pdf(self, excel_path, file_name):
        # excel_path = excel_path.replace(os.path.split(excel_path)[1], file_name)
        print(excel_path)
        input_file_name = os.path.basename(excel_path)
        return_pdf_name = input_file_name.replace(".xlsx", ".pdf").replace(".xls", ".pdf")
        data = "%s_%d" % (return_pdf_name, int(time.time()))
        file_hash = hashlib.sha1(data.encode("utf8")).hexdigest()
        time_dir = time.strftime("%Y/%m/%d/", time.localtime())
        file_full_path = time_dir + str(file_hash)
        pdf_path = 'media/pdf_path/' + file_full_path
        file_path = os.path.join(os.getcwd(), pdf_path)
        if not os.path.exists(file_path):
            os.makedirs(file_path)

        pythoncom.CoInitialize()
        excel = Dispatch("Excel.Application")

        excel.Visible = 0  # xls文件不可见
        excel.DisplayAlerts = 0
        sheets = excel.Workbooks.Open(excel_path, False)

        print(excel_path)
        i = 0
        path_list = []
        try:
            while i < len(sheets.Worksheets):
                work_sheet = sheets.Worksheets[i]
                work_sheet.PageSetup.Orientation = 2
                work_sheet.Select()
                work_sheet.PageSetup.Zoom = False
                work_sheet.PageSetup.FitToPagesWide = 2       # 以适应宽度的方式缩放
                title = work_sheet.Name.replace(" ", "_")
                pdf_file_path = file_path + '/' + file_name.split('.')[0] + "_" + title + ".pdf"
                work_sheet.ExportAsFixedFormat(0, pdf_file_path)
                path_list.append(pdf_file_path)
                i += 1
            sheets.Close(True)
        except Exception as E:
            print(E)
            path_list.append(excel_path)
            sheets.Close(True)
        return path_list

    def word2pdf(self, input_file_path, types=1):
        input_file_name = os.path.basename(input_file_path)
        return_pdf_name = input_file_name.replace(f".{input_file_path.split('.')[-1]}", ".pdf")
        data = "%s_%d" % (return_pdf_name, int(time.time()))
        file_hash = hashlib.sha1(data.encode("utf8")).hexdigest()
        time_dir = time.strftime("%Y/%m/%d/", time.localtime())
        file_full_path = time_dir + str(file_hash)
        pdf_path = 'media/pdf_path/' + file_full_path
        if types == 2:
            pdf_path = 'static/administrative/UploadAccessory/main_body/shouwen/' + time.strftime("%m", time.localtime()) + "/pdf_dir/" + file_full_path
        file_path = os.path.join(os.getcwd(), pdf_path)
        if not os.path.exists(file_path):
            os.makedirs(file_path)

        # if client is None:  # 判断环境，linux环境这里肯定为None
        #     self.doc2pdf_linux(input_file_path, file_path)
        #     return '/' + pdf_path + '/' + return_pdf_name

        if input_file_path.endswith(".doc") or input_file_path.endswith(".docx") or input_file_path.endswith(".DOC") or input_file_path.endswith(".DOCX"):
            print(input_file_path)
            if os.path.exists(input_file_path.replace("/", "\\")):
                print("文件存在")

            # os.system('taskkill /f /t /im wpscloudsvr.exe')
            pythoncom.CoInitialize()
            word = DispatchEx('kwps.Application')
            doc = word.Documents.Open(input_file_path)
            print("input_file_path>>>>>>>>>>>> ", file_path + '/' + return_pdf_name)
            doc.SaveAs(file_path + '/' + return_pdf_name, FileFormat=17)
            doc.Close()
            word.Quit()
            # word.close()

        return_pdf_path = '/' + pdf_path + '/' + return_pdf_name
        print(return_pdf_path)
        return return_pdf_path

    def ppt2pdf(self, input_file_path):
        """
            PPT文件导出为pdf格式
            :param filename: PPT文件的名称
            :param output_filename: 导出的pdf文件的名称
            :return:
            """
        input_file_name = os.path.basename(input_file_path)
        return_pdf_name = input_file_name.replace(".pptx", ".pdf").replace(".ppt", ".pdf")
        data = "%s_%d" % (return_pdf_name, int(time.time()))
        file_hash = hashlib.sha1(data.encode("utf8")).hexdigest()
        time_dir = time.strftime("%Y/%m/%d/", time.localtime())
        file_full_path = time_dir + str(file_hash)
        pdf_path = 'media/pdf_path/' + file_full_path
        file_path = os.path.join(os.getcwd(), pdf_path)
        if not os.path.exists(file_path):
            os.makedirs(file_path)

        pythoncom.CoInitialize()
        ppt_app = Dispatch('PowerPoint.Application')

        ppt = ppt_app.Presentations.Open(input_file_path)
        ppt.SaveAs(file_path + '/' + return_pdf_name, 32)
        # 退出PPT程序
        ppt_app.Quit()
        # ppt_app.close()
        return_pdf_path = '/' + pdf_path + '/' + return_pdf_name
        return return_pdf_path

    def doc2pdf_linux(self, docPath, pdfPath):
        """
        convert a doc/docx document to pdf format (linux only, requires libreoffice)
        :param doc: path to document
        """
        cmd = 'libreoffice7.0 --headless --convert-to pdf'.split() + [docPath] + ['--outdir'] + [pdfPath]
        p = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
        p.wait(timeout=30)
        stdout, stderr = p.communicate()
        if stderr:
            raise subprocess.SubprocessError(stderr)
        return pdfPath


# excel转pdf
class PDFConverter:
    def __init__(self, pathname, sheetnum, file_name):
        self.sheetnum = sheetnum
        self._handle_postfix = ['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx']
        self._filename_list = list()
        self.file_name = file_name
        print(pathname)
        input_file_name = os.path.basename(pathname)
        return_pdf_name = input_file_name.replace(".xlsx", ".pdf").replace(".xls", ".pdf")
        data = "%s_%d" % (return_pdf_name, int(time.time()))
        file_hash = hashlib.sha1(data.encode("utf8")).hexdigest()
        time_dir = time.strftime("%Y/%m/%d/", time.localtime())
        file_full_path = time_dir + str(file_hash)
        pdf_path = 'media/pdf_path/' + file_full_path
        self._export_folder = os.path.join(os.getcwd(), pdf_path)
        if not os.path.exists(self._export_folder):
            os.makedirs(self._export_folder)
        self._enumerate_filename(pathname)

    def _enumerate_filename(self, pathname):
        '''
        读取所有文件名
        '''
        full_pathname = os.path.abspath(pathname)
        if os.path.isfile(full_pathname):
            if self._is_legal_postfix(full_pathname):
                self._filename_list.append(full_pathname)
            else:
                raise TypeError('文件 {} 后缀名不合法！仅支持如下文件类型：{}。'.format(pathname, '、'.join(self._handle_postfix)))
        elif os.path.isdir(full_pathname):
            for relpath, _, files in os.walk(full_pathname):
                for name in files:
                    filename = os.path.join(full_pathname, relpath, name)
                    if self._is_legal_postfix(filename):
                        self._filename_list.append(os.path.join(filename))
        else:
            raise TypeError('文件/文件夹 {} 不存在或不合法！'.format(pathname))

    def _is_legal_postfix(self, filename):
        return filename.split('.')[-1].lower() in self._handle_postfix and not os.path.basename(filename).startswith(
            '~')

    def run_conver(self):
        '''
        进行批量处理，根据后缀名调用函数执行转换
        '''
        print('需要转换的文件数：', len(self._filename_list))
        for filename in self._filename_list:
            postfix = filename.split('.')[-1].lower()
            funcCall = getattr(self, postfix)
            print('原文件：', filename)
            path_list = funcCall(filename)
            print('转换完成！', path_list)
            return path_list

    def xls(self, filename):
        '''
        xls 和 xlsx 文件转换
        '''
        pythoncom.CoInitialize()
        xlApp = DispatchEx("Excel.Application")
        xlApp.Visible = False
        xlApp.DisplayAlerts = 0
        books = xlApp.Workbooks.Open(filename, False)
        # 循环保存每一个sheet
        path_list = []
        for i in range(1, self.sheetnum + 1):
            sheetName = books.Sheets(i).Name
            xlSheet = books.Worksheets(sheetName)
            name = sheetName + '.pdf'
            exportfile = self._export_folder + "/" + self.file_name + "_" + name
            xlSheet.ExportAsFixedFormat(0, exportfile)
            print('保存 PDF 文件：', exportfile)
            path_list.append(exportfile)
        books.Close(False)
        xlApp.Quit()
        return path_list

    def xlsx(self, filename):
        print("开始转换")
        return self.xls(filename)


class ParseIssueWORD():

    def replace_issue_type(self,doc, newtext):
        for j in range(len(doc.paragraphs)):
            if j == 0:
                inline = doc.paragraphs[j].runs
                for i in range(len(inline)):
                    if i == 0:
                        print('i.text:', inline[i].text)
                        text = inline[i].text.replace(inline[i].text, newtext)
                        inline[i].text = text
                    else:
                        inline[i].text = ''

    def replace_issue_number(self,doc, newtext):
        for para in doc.paragraphs:
            for i in range(len(para.runs)):
                if '议题编号' in para.text:
                    inline = para.runs
                    for i in range(len(inline)):
                        if i == 0:
                            text = inline[i].text.replace(inline[i].text, newtext)
                            inline[i].text = text
                        else:
                            inline[i].text = ''

    def add_leader1_pic(self,doc, pic):
        paragraphs = doc.tables[0].cell(0, 3).paragraphs
        c_p1 = paragraphs[0]
        c_p1.paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER  # 设置单元格内容居中对齐
        c_run1 = c_p1.add_run()
        if os.path.exists(pic):
            c_run1.add_picture(pic, width=Cm(2))

    def add_leader2_pic(self,doc,pic):
        paragraphs = doc.tables[0].cell(6, 1).paragraphs
        c_p1 = paragraphs[1]
        c_p1.paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER  # 设置单元格内容居中对齐
        c_run1 = c_p1.add_run()
        c_run1.add_picture(pic, width=Cm(2))

    def add_leader3_pic(self,doc,pic):
        paragraphs = doc.tables[0].cell(7, 1).paragraphs
        c_p1 = paragraphs[1]
        c_p1.paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER  # 设置单元格内容居中对齐
        c_run1 = c_p1.add_run()
        c_run1.add_picture(pic, width=Cm(2))

    def add_pic(self,doc, x, y, pic):
        paragraphs = doc.tables[0].cell(x, y).paragraphs
        c_p1 = paragraphs[0]
        c_p1.paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER  # 设置单元格内容居中对齐
        c_run1 = c_p1.add_run()
        if os.path.exists(pic):
            if os.path.isfile(pic):
                c_run1.add_picture(pic, width=Cm(1))

    def replace_text_new(self,doc, x, y, newtext):
        paragraphs = doc.tables[0].cell(x, y).paragraphs
        for p in paragraphs:
            inline = p.runs
            not_line = False
            if not inline:
                p.add_run()
                not_line = True
            inline = p.runs
            for i in range(len(inline)):
                if i == 0:
                    text = inline[i].text.replace(inline[i].text, newtext)
                    inline[i].text = text
                    if not_line:
                        inline[i].font.name = '仿宋_GB2312'
                        inline[i].font.size = 177800
                        inline[i].element.rPr.rFonts.set(qn('w:eastAsia'), u'仿宋_GB2312')
                else:
                    inline[i].text = ''
        print('*-' * 30)

    def replace_leader2_text(self,doc, x, y, newtext, approval_date):
        paragraphs = doc.tables[0].cell(x, y).paragraphs
        for j in range(len(paragraphs)):
            if j == 0:
                if '年' not in paragraphs[j].text:
                    inline = paragraphs[j].runs
                    not_line = False
                    if not inline:
                        paragraphs[j].add_run()
                        not_line = True
                    inline = paragraphs[j].runs
                    for i in range(len(inline)):
                        if i == 0:
                            text = inline[i].text.replace(inline[i].text, newtext)
                            inline[i].text = text
                            if not_line:
                                inline[i].font.name = '仿宋_GB2312'
                                inline[i].font.size = 177800
                                inline[i].element.rPr.rFonts.set(qn('w:eastAsia'), u'仿宋_GB2312')
                        else:
                            inline[i].text = ''
            else:
                if '年' in paragraphs[j].text:
                    inline = paragraphs[j].runs
                    not_line = False
                    if not inline:
                        paragraphs[j].add_run()
                        not_line = True
                    inline = paragraphs[j].runs
                    for i in range(len(inline)):
                        if i == 1:
                            if approval_date:
                                text = inline[i].text.replace(inline[i].text, '           '+approval_date.split('-')[0])
                                inline[i].text = text
                                if not_line:
                                    inline[i].font.name = '仿宋_GB2312'
                                    inline[i].font.size = 177800
                                    inline[i].element.rPr.rFonts.set(qn('w:eastAsia'), u'仿宋_GB2312')
                        if i == 3:
                            if approval_date:
                                text = inline[i].text.replace(inline[i].text, approval_date.split('-')[1])
                                inline[i].text = text
                                if not_line:
                                    inline[i].font.name = '仿宋_GB2312'
                                    inline[i].font.size = 177800
                                    inline[i].element.rPr.rFonts.set(qn('w:eastAsia'), u'仿宋_GB2312')
                        if i == 5:
                            if approval_date:
                                text = inline[i].text.replace(inline[i].text, approval_date.split('-')[2])
                                inline[i].text = text
                                if not_line:
                                    inline[i].font.name = '仿宋_GB2312'
                                    inline[i].font.size = 177800
                                    inline[i].element.rPr.rFonts.set(qn('w:eastAsia'), u'仿宋_GB2312')

    def replace_leader3_text(self,doc, x, y, newtext, approval_date):
        paragraphs = doc.tables[0].cell(x, y).paragraphs
        for j in range(len(paragraphs)):
            if j == 0:
                if '年' not in paragraphs[j].text:
                    inline = paragraphs[j].runs
                    not_line = False
                    if not inline:
                        paragraphs[j].add_run()
                        not_line = True
                    inline = paragraphs[j].runs
                    for i in range(len(inline)):
                        if i == 0:
                            text = inline[i].text.replace(inline[i].text, newtext)
                            inline[i].text = text
                            if not_line:
                                inline[i].font.name = '仿宋_GB2312'
                                inline[i].font.size = 177800
                                inline[i].element.rPr.rFonts.set(qn('w:eastAsia'), u'仿宋_GB2312')
                        else:
                            inline[i].text = ''
            else:
                if '年' in paragraphs[j].text:
                    inline = paragraphs[j].runs
                    not_line = False
                    if not inline:
                        paragraphs[j].add_run()
                        not_line = True
                    inline = paragraphs[j].runs
                    for i in range(len(inline)):
                        if i == 0:
                            if approval_date:
                                text = inline[i].text.replace('年', approval_date.split('-')[0] + '年')
                                inline[i].text = text
                                if not_line:
                                    inline[i].font.name = '仿宋_GB2312'
                                    inline[i].font.size = 177800
                                    inline[i].element.rPr.rFonts.set(qn('w:eastAsia'), u'仿宋_GB2312')
                        if i == 1:
                            if approval_date:
                                text = inline[i].text.replace(inline[i].text, approval_date.split('-')[1])
                                inline[i].text = text
                                if not_line:
                                    inline[i].font.name = '仿宋_GB2312'
                                    inline[i].font.size = 177800
                                    inline[i].element.rPr.rFonts.set(qn('w:eastAsia'), u'仿宋_GB2312')
                        if i == 3:
                            if approval_date:
                                text = inline[i].text.replace(inline[i].text, approval_date.split('-')[2])
                                inline[i].text = text
                                if not_line:
                                    inline[i].font.name = '仿宋_GB2312'
                                    inline[i].font.size = 177800
                                    inline[i].element.rPr.rFonts.set(qn('w:eastAsia'), u'仿宋_GB2312')

    def parse_codepartment(self,doc, co_li):
        for j in range(len(co_li)):
            self.replace_text_new(doc, 3 + j, 1, co_li[j]['sponsor'])
            self.add_pic(doc, 3 + j, 4, co_li[j]['autograph_url'])

    def parse_leader2(self,doc,approval_date,opinion,pic):
        self.replace_leader2_text(doc, 6, 1, opinion, approval_date)
        if os.path.exists(pic):
            if os.path.isfile(pic):
                self.add_leader2_pic(doc,pic)

    def parse_leader3(self,doc,approval_date,opinion,pic):
        self.replace_leader3_text(doc, 7, 1, opinion, approval_date)
        if os.path.exists(pic):
            if os.path.isfile(pic):
                self.add_leader3_pic(doc,pic)

    def run(self,item):
        doc = docx.Document(item['docx_path'])
        # self.replace_issue_type(doc, item['issue_type'])
        self.replace_issue_number(doc, '议题编号： '+item['issue_number'])
        self.replace_text_new(doc, 0, 1, item['submission_department'])
        self.add_leader1_pic(doc,item['leader1_pic'])
        self.replace_text_new(doc, 0, 5, item['submission_date'])
        self.replace_text_new(doc, 1, 1, item['topics'])
        self.replace_text_new(doc, 2, 1, item['key_issues'])
        self.parse_codepartment(doc, item['co_li'])
        self.parse_leader2(doc,item['leader2_date'],item['leader2_opinion'],item['leader2_pic'])
        self.parse_leader3(doc,item['leader3_date'],item['leader3_opinion'],item['leader3_pic'])

        new_path = item['docx_path'].replace('.docx','_new.docx')
        # doc.save(item['docx_path'])
        doc.save(new_path)
        return new_path

    def add_word_text(self,word_path):
        doc2 = Document(word_path)

        for i in range(len(doc2.paragraphs)):
            doc2.paragraphs[i].paragraph_format.space_before = Pt(0)
            doc2.paragraphs[i].paragraph_format.space_after = Pt(0)
            style_name = doc2.paragraphs[i].style.name
            if i > 0:
                if style_name in ['Heading 4', "Body Text Indent 2", "Normal (Web)"]:
                    doc2.paragraphs[i].height = Pt(28)
                    doc2.paragraphs[i].height_rule = WD_ROW_HEIGHT_RULE.EXACTLY

                    inline = doc2.paragraphs[i].runs
                    for i in inline:
                        i.font.italic = False
                        i.font.color.rgb = RGBColor(0, 0, 0)
                        i.font.bold = False
                        text = i.text
                        i.text = text
        return doc2

    def word_file_save(self,doc_path):
        try:
            word = DispatchEx('Word.Application')  # 启动独立的进程
        except:
            pythoncom.CoInitialize()
            word = DispatchEx('Word.Application') #启动独立的进程
        word.Visible = 0  # 后台运行,不显示
        word.DisplayAlerts = 0  # 不警告
        doc = word.Documents.Open(FileName=doc_path, Encoding='gbk')
        new_docx_path = doc_path.replace('.docx','-.docx')
        doc.SaveAs(new_docx_path,FileFormat=16)

        try:
            doc.Close()  # 关闭word文档
            word.Quit()
        except:
            print('关闭失败')
        # os.system('taskkill /f /t /im WINWORD.exe')
        return new_docx_path


    def run_temp(self,item):
        # 复制模板
        new_copy_docx_path = item['docx_path'].replace('.docx','_new.docx')
        print('item[temp_path]:', item['temp_path'])
        shutil.copy(item['temp_path'],new_copy_docx_path)

        doc = docx.Document(new_copy_docx_path)
        self.replace_issue_number(doc, '议题编号： '+item['issue_number'])
        self.replace_text_new(doc, 0, 1, item['submission_department'])
        self.add_leader1_pic(doc,item['leader1_pic'])
        self.replace_text_new(doc, 0, 5, item['submission_date'])
        self.replace_text_new(doc, 1, 1, item['topics'])
        self.replace_text_new(doc, 2, 1, item['key_issues'])
        self.parse_codepartment(doc, item['co_li'])
        self.parse_leader2(doc,item['leader2_date'],item['leader2_opinion'],item['leader2_pic'])
        self.parse_leader3(doc,item['leader3_date'],item['leader3_opinion'],item['leader3_pic'])

        composer = Composer(doc)
        new_docx_path = self.word_file_save(item['docx_path'])
        doc2 = self.add_word_text(new_docx_path)
        composer.append(doc2)
        composer.save(new_copy_docx_path)
        print('*--*'*50)
        return new_copy_docx_path

    def create_issue_table(self,item):
        # 复制模板
        new_copy_docx_path = item['docx_path'].replace('.docx', '_new.docx')
        print('item[temp_path]:', item['temp_path'])
        shutil.copy(item['temp_path'], new_copy_docx_path)

        doc = docx.Document(new_copy_docx_path)
        self.replace_issue_number(doc, '议题编号： ' + item['issue_number'])
        self.replace_text_new(doc, 0, 1, item['submission_department'])
        self.add_leader1_pic(doc, item['leader1_pic'])
        self.replace_text_new(doc, 0, 5, item['submission_date'])
        self.replace_text_new(doc, 1, 1, item['topics'])
        self.replace_text_new(doc, 2, 1, item['key_issues'])
        self.parse_codepartment(doc, item['co_li'])
        self.parse_leader2(doc, item['leader2_date'], item['leader2_opinion'], item['leader2_pic'])
        self.parse_leader3(doc, item['leader3_date'], item['leader3_opinion'], item['leader3_pic'])
        doc.save(new_copy_docx_path)
        return new_copy_docx_path


# excel转pdf
class PDFConverter:
    def __init__(self, pathname, sheetnum, file_name):
        self.sheetnum = sheetnum
        self._handle_postfix = ['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx']
        self._filename_list = list()
        self.file_name = file_name
        print(pathname)
        input_file_name = os.path.basename(pathname)
        return_pdf_name = input_file_name.replace(".xlsx", ".pdf").replace(".xls", ".pdf")
        data = "%s_%d" % (return_pdf_name, int(time.time()))
        file_hash = hashlib.sha1(data.encode("utf8")).hexdigest()
        time_dir = time.strftime("%Y/%m/%d/", time.localtime())
        file_full_path = time_dir + str(file_hash)
        pdf_path = 'media/pdf_path/' + file_full_path
        self._export_folder = os.path.join(os.getcwd(), pdf_path)
        if not os.path.exists(self._export_folder):
            os.makedirs(self._export_folder)
        self._enumerate_filename(pathname)

    def _enumerate_filename(self, pathname):
        '''
        读取所有文件名
        '''
        full_pathname = os.path.abspath(pathname)
        if os.path.isfile(full_pathname):
            if self._is_legal_postfix(full_pathname):
                self._filename_list.append(full_pathname)
            else:
                raise TypeError('文件 {} 后缀名不合法！仅支持如下文件类型：{}。'.format(pathname, '、'.join(self._handle_postfix)))
        elif os.path.isdir(full_pathname):
            for relpath, _, files in os.walk(full_pathname):
                for name in files:
                    filename = os.path.join(full_pathname, relpath, name)
                    if self._is_legal_postfix(filename):
                        self._filename_list.append(os.path.join(filename))
        else:
            raise TypeError('文件/文件夹 {} 不存在或不合法！'.format(pathname))

    def _is_legal_postfix(self, filename):
        return filename.split('.')[-1].lower() in self._handle_postfix and not os.path.basename(filename).startswith(
            '~')

    def run_conver(self):
        '''
        进行批量处理，根据后缀名调用函数执行转换
        '''
        print('需要转换的文件数：', len(self._filename_list))
        for filename in self._filename_list:
            postfix = filename.split('.')[-1].lower()
            funcCall = getattr(self, postfix)
            print('原文件：', filename)
            path_list = funcCall(filename)
            print('转换完成！', path_list)
            return path_list

    def xls(self, filename):
        '''
        xls 和 xlsx 文件转换
        '''
        pythoncom.CoInitialize()
        xlApp = DispatchEx("Excel.Application")
        xlApp.Visible = False
        xlApp.DisplayAlerts = 0
        books = xlApp.Workbooks.Open(filename, False)
        # 循环保存每一个sheet
        path_list = []
        for i in range(1, self.sheetnum + 1):
            sheetName = books.Sheets(i).Name
            xlSheet = books.Worksheets(sheetName)
            name = sheetName + '.pdf'
            exportfile = self._export_folder + "/" + self.file_name + "_" + name
            xlSheet.ExportAsFixedFormat(0, exportfile)
            print('保存 PDF 文件：', exportfile)
            path_list.append(exportfile)
        books.Close(False)
        xlApp.Quit()
        return path_list

    def xlsx(self, filename):
        print("开始转换")
        return self.xls(filename)



if __name__ == '__main__':
    # file_type = '3'
    # fwh = '京〔66668888〕号'
    # word_path = './static/administrative/UploadAccessory/demo1111.docx'
    # ParseWord().start_parse(file_type,word_path,fwh)
    print(ParseWord().word2pdf(r'D:\Users\hhr\ProjectPycharm\pythonProject\my_test\files\关于表彰2021年度先进集体和先进工作者的通知.docx'))
